﻿using System;
using System.Linq;
using ZDV.IdentityModel.Tools;
using ZDV.IdentityModel.Tools.Serialization;

namespace ZDV.IdentityModel.IssuerNameRegistryUpdater
{
    class Program
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetLogger("INRUpdater");

        static void Main(string[] args)
        {
            Logger.Info("## Issuer Name Registry Updater has been startet. ##");

            var cmdOptions = new CommandLineOptions();
            if (CommandLine.CommandLineParser.Default.ParseArguments(args, cmdOptions))
            {
                cmdOptions.BaseDirectory  = cmdOptions.BaseDirectory ?? Environment.CurrentDirectory;
                TraceCommandLineOptions(cmdOptions);

                var metadata = new Metadata(cmdOptions.MetadataLocation);

                TraceMetadata(metadata);
                
                foreach (var configFileItem in cmdOptions.ConfigurationFiles)
                {
                    var configFileParts = configFileItem.Split(new [] { '#' }, 2);

                    var configFile = configFileParts[0];
                    var serviceName = (configFileParts.Length > 1)? configFileParts[1] : null;

                    var configFilePath = System.IO.Path.Combine(cmdOptions.BaseDirectory, configFile);
                    Logger.Info("## Updating File: {0} ##", configFilePath);

                    var configWorker = new ConfigurationHandler(configFilePath);

                    configWorker.UpdateIssuerNameRegistryElement(
                        serviceName,
                        metadata.SecurityTokenServiceSigningCertificates,
                        metadata.IssuerName);

                    configWorker.FlushDocument();
                }
            }

            Logger.Info("## Issuer Name Registry Updater has finished. ##");
        }

        private static void TraceCommandLineOptions(CommandLineOptions cmdOptions)
        {
            Logger.Trace("--Command Line Options--");
            Logger.Trace("MetadataLocation: {0}", cmdOptions.MetadataLocation);
            Logger.Trace("BaseDirectory: {0}", cmdOptions.BaseDirectory);
            Logger.Trace("ConfigurationFiles: \"{0}\"", String.Join("\", \"", cmdOptions.ConfigurationFiles));
        }

        private static void TraceMetadata(Metadata metadata)
        {
            Logger.Trace("-- Metadata Information --");
            Logger.Trace("IssuerName: {0}", metadata.IssuerName);
            Logger.Trace("Certificates: {0}", String.Join("; ", metadata.SecurityTokenServiceSigningCertificates
                .Select(cert => String.Format("Thumbprint: {0}, SubjectName: {1}", cert.Thumbprint, cert.SubjectName))));
                
        }
    }
}
